package com.fishingwithme.android.ui.screens.auth

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.R
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.components.AppTitle
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.AuthViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(
    _navController: NavController,
    viewModel: AuthViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    var passwordVisible by remember { mutableStateOf(false) }

    // Get current context
    val context = androidx.compose.ui.platform.LocalContext.current

    // Handle result from AgreementPolicyScreen
    val agreementPolicyResult =
        _navController.currentBackStackEntry?.savedStateHandle?.get<String>("agreedType")
    LaunchedEffect(agreementPolicyResult) {
        agreementPolicyResult?.let { type ->
            when (type) {
                "AD_PP" -> viewModel.setPrivacyPolicyChecked(true)
                "AD_UA" -> viewModel.setUserAgreementChecked(true)
            }
            // Clear the result after handling it
            _navController.currentBackStackEntry?.savedStateHandle?.remove<String>("agreedType")
        }
    }

    // Handle login success - navigate to MainActivity when logged in
    LaunchedEffect(uiState.isLoggedIn) {
        if (uiState.isLoggedIn) {
            // Start MainActivity to show the main interface with bottom navigation
            val intent =
                android.content.Intent(context, com.fishingwithme.android.MainActivity::class.java)
            intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK)
            context.startActivity(intent)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(AppDimensions.SPACING_16),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // App Title Component
        AppTitle()
        // Login Card
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = AppDimensions.SPACING_16),
            shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_12),
            elevation = CardDefaults.cardElevation(AppDimensions.CARD_ELEVATION_4)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(AppDimensions.SPACING_16),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = stringResource(R.string.login),
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(bottom = AppDimensions.SPACING_24)
                )

                // Username Field
                OutlinedTextField(
                    value = uiState.username,
                    onValueChange = { viewModel.setUsername(it) },
                    label = { Text("用户名/手机号") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = AppDimensions.SPACING_16),
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                    textStyle = TextStyle(color = MaterialTheme.colorScheme.onSurface),
                    shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
                )

                // Password Field
                OutlinedTextField(
                    value = uiState.password,
                    onValueChange = { viewModel.setPassword(it) },
                    label = { Text(stringResource(R.string.password)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = AppDimensions.SPACING_16),
                    singleLine = true,
                    visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                    textStyle = TextStyle(color = MaterialTheme.colorScheme.onSurface),
                    shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8),
                    trailingIcon = {
                        val image = if (passwordVisible)
                            Icons.Filled.Visibility
                        else Icons.Filled.VisibilityOff

                        IconButton(onClick = { passwordVisible = !passwordVisible }) {
                            Icon(imageVector = image, contentDescription = null)
                        }
                    }
                )

                // Login Button
                Button(
                    onClick = {
                        viewModel.login()
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = AppDimensions.SPACING_16)
                        .height(50.dp),
                    enabled = uiState.username.isNotBlank() && uiState.password.isNotBlank() &&
                            uiState.isPrivacyPolicyChecked && uiState.isUserAgreementChecked &&
                            !uiState.isLoading,
                    colors = ButtonDefaults.buttonColors(),
                    shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
                ) {
                    if (uiState.isLoading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(AppDimensions.ICON_SIZE_20),
                            color = MaterialTheme.colorScheme.onPrimary
                        )
                    } else {
                        Text(stringResource(R.string.login))
                    }
                }

                // Privacy Policy and User Agreement Checkboxes
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = AppDimensions.SPACING_16),
                    verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_4)
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Checkbox(
                            checked = uiState.isPrivacyPolicyChecked,
                            onCheckedChange = { viewModel.setPrivacyPolicyChecked(it) }
                        )
                        TextButton(onClick = {
                            _navController.navigate("${FishingNavigation.AGREEMENT_POLICY}?type=AD_PP")
                        }) {
                            Text(stringResource(R.string.view_and_agree_policy))
                        }
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Checkbox(
                            checked = uiState.isUserAgreementChecked,
                            onCheckedChange = { viewModel.setUserAgreementChecked(it) }
                        )
                        TextButton(onClick = {
                            _navController.navigate("${FishingNavigation.AGREEMENT_POLICY}?type=AD_UA")
                        }) {
                            Text(stringResource(R.string.view_and_agree_agreement))
                        }
                    }
                }

                // Error Message
                uiState.error?.let { error ->
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = AppDimensions.SPACING_16),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.errorContainer
                        )
                    ) {
                        Text(
                            text = stringResource(R.string.error_invalid_credentials),
                            modifier = Modifier.padding(AppDimensions.SPACING_16),
                            color = MaterialTheme.colorScheme.onErrorContainer,
                            textAlign = TextAlign.Center
                        )
                    }
                }

                // Register/Forgot Password Links
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(onClick = { 
                        _navController.navigate(FishingNavigation.REGISTER)
                    }) {
                        Text(stringResource(R.string.register_account))
                    }

                    TextButton(onClick = { /* Navigate to forgot password */ }) {
                        Text(stringResource(R.string.forgot_password))
                    }
                }
            }
        }
    }
}